
<template>
  <div id="oder-list" class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form :inline="true" ref="ruleForm">
        <el-form-item>
          <el-button
            icon="el-icon-circle-plus-outline"
            type="button"
            class="el-button el-button--primary"
            @click="
              dialogFormVisible = true;
              diaTitle = '角色创建';
              isCreate = 'true';
            "
          >
            创建角色</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="button"
            icon="el-icon-delete"
            class="el-button el-button--danger"
            @click="batchDelRole"
          >
            批量删除角色</el-button
          >
        </el-form-item>
        <el-form-item v-if="selection">
          <el-button
            type="button"
            class="el-button el-button--danger"
            @click="sbumitDel"
          >
            确认批量删除</el-button
          >
        </el-form-item>

        <el-form-item v-if="selection">
          <el-button
            type="button"
            class="el-button el-button--priamry"
            @click="cancelDel"
          >
            取消批量删除</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchMain"
            placeholder="请输入角色名"
            @keyup.enter.native="searchRole()"
            clearable
            @clear="clear"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="button"
            class="el-button el-button--primary"
            @click="searchRole()"
          >
            查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      element-loading-text="给我一点时间"
      style="width: 100%"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="SelectionChange"
    >
      <el-table-column
        type="selection"
        v-if="selection"
        width="30"
      ></el-table-column>
      <el-table-column type="index" label="序号"> </el-table-column>
      <el-table-column prop="name" label="角色名称"></el-table-column>
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column prop="description" label="说明"></el-table-column>
      <el-table-column prop="adminCount" label="后台用户数量"></el-table-column>
      <el-table-column prop="status" label="是否使用">
        <template slot-scope="scope">
          <!-- {{ scope.row.status == 1 ? "是" : "否" }} -->
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="0"
            @change="editStatus(scope.row.id,scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime | parseTime }}
        </template>
      </el-table-column> -->
      <el-table-column prop="operate" align="center" label="操作" width="400">
        <template slot-scope="scope">
          <div class="fx" style="display: flex">
            <el-button
              @click="editRole(scope.row)"
              type="button"
              icon="el-icon-edit"
              class="el-button el-button--primary"
              >修改</el-button
            >
            <el-button
              @click="getRoleResources(scope.row)"
              type="button"
              class="el-button el-button--primary"
              >分配资源</el-button
            >
            <el-button
              @click="getRoleMenu(scope.row)"
              type="button"
              class="el-button el-button--primary"
              >分配菜单</el-button
            >
            <el-button
              type="button"
              icon="el-icon-delete"
              class="el-button el-button--danger"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- //新增 修改 -->
    <el-dialog
      :title="diaTitle"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <!-- <el-form :model="createForm" :rules="rules" ref="form"> -->
      <el-form :model="createForm" :rules="rules" ref="createForm">
        <el-form-item prop="name" label="角色" :label-width="formLabelWidth">
          <el-input v-model="createForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item
          prop="description"
          label="角色描述"
          :label-width="formLabelWidth"
        >
          <el-input
            type="textarea"
            v-model="createForm.description"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="status"
          label="是否启用"
          :label-width="formLabelWidth"
        >
          <el-switch
            v-model="createForm.status"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="0"
            @change="statusChange(createForm.status)"
          >
          </el-switch>
        </el-form-item>
        <!-- <el-form-item prop="id"  :label-width="formLabelWidth">
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              v-if="isCreate == 'true'"
              type="primary"
              @click="submitForm()"
              >创建</el-button
            >
            <el-button v-else type="primary" @click="edit(id)">修改</el-button>
          </div>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="isCreate == 'true'"
          type="primary"
          @click="submitForm('createForm')"
          >创建</el-button
        >
        <el-button icon="el-icon-edit" v-else type="primary" @click="edit('createForm')">修改</el-button>
      </div>
    </el-dialog>
    <!-- 资源分配 -->
    <el-dialog
      title="资源分配"
      :visible.sync="resourcesShow"
      @close="closeDialog"
      width="50%"
      v-loading="loading"
    >
      <el-form :model="resourcesForm">
        <el-form-item
          prop="name"
          label="资源节点"
          :label-width="formLabelWidth"
        >
          <el-tree
            :data="resourcesData"
            :props="resourcesProps"
            node-key="id"
            show-checkbox
            ref="resource"
            :default-checked-keys="this.currentResources"
            @check="resourcesCheck"
          >
            ></el-tree
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resourcesAllocation()"
          >分配资源</el-button
        >
      </div>
    </el-dialog>
    <!-- 菜单分配 -->
    <el-dialog
      title="菜单分配"
      :visible.sync="menuShow"
      @close="closeDialog"
      width="50%"
      v-loading="loading"
    >
      <el-form :model="resourcesForm">
        <el-form-item
          prop="name"
          label="菜单节点"
          :label-width="formLabelWidth"
        >
          <el-tree
            :data="menuData"
            :props="menuProps"
            node-key="id"
            show-checkbox
            ref="tree"
            :default-checked-keys="this.currentMenu"
            @check="menuCheck"
          >
            ></el-tree
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="menuAllocation()">分配菜单</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40, 100, 300, 500]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div> -->
  </div>
</template>

<script>
import {
  AllRole,
  createRole,
  editRole,
  selectionDelRole,
  getListResource,
  allResource,
  setResource,
  editRoleStatus,
  searchResource,
  getListMenu,
  setMenu,
  searchRole,
  
} from "@/api/role";
import {allMenuList} from "@/api/menu"
export default {
  data() {
    return { 
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "change" },
        ],
        description: [
          { required: true, message: "请输入角色描述", trigger: "change" },
        ]
      },
      loading: false,
      total: 0,
      pageNum: 1,
      pageSize: 50,
      searchMain: "", //搜索框内容
      roleID: "",
      currentResources: [], //当前角色资源
      currentMenu: [], //当前角色菜单
      resourcesIds: [], //分配的资源数组
      resourcesForm: {
        //资源表单
        name: "",
      },
      resourcesData: [], //资源列表
      resourcesProps: {
        children: "children",
        label: "name",
      },
      menuData: [], //菜单列表
      menuProps: {
        children: "children",
        label: "title",
      },
      resourcesShow: false, //分配资源弹窗
      menuShow: false, //分配资源弹窗
      delIds: [],
      selection: false, //批量操作checkbox显示
      editID: "",
      isCreate: "",
      diaTitle: "",
      dialogFormVisible: false,
      formLabelWidth: "140px",
      tableData: [],
      createForm: {
        adminCount: "", //后台角色数量
        description: "", //角色描述
        name: "", //角色名称
        status: 1, //禁用/启用
      },
    };
  },
  methods: {
    deleteRole(id) {
      // console.log(id);
      this.$confirm("确定删除此角色", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await selectionDelRole({ ids: id });
          if (res.code == 1) {
            this.$message.success("删除角色成功");
            this.getAllRole();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    clear() {
      this.getAllRole();
    },
    sizeChange(val) {
      this.pageSize = val;
      this.searchRole();
    },
    currentChange(val) {
      this.pageNum = val;
      this.searchRole();
    },
    // 模糊查询
    async searchRole() {
      let query = {
        keyword: this.searchMain,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      let res = await searchRole(query);
      this.tableData = res.data;
      // if()
      // if (this.searchMain.length<1) {
      //   this.AllRole()
      // }
      // console.log(res);
    },
    // 资源节点选择
    resourcesCheck(data, checked) {
      let tree = this.$refs.resource.getCheckedNodes(false,true);
      this.resourcesIds = [];
      tree.map((item) => {
        if (item.categoryId) {
          this.resourcesIds.push(item.id);
        }
      });
    },
    // 菜单节点选择
    menuCheck(data, checked) {
      let tree = this.$refs.tree.getCheckedNodes(false,true);
      console.log(tree);

      this.menuIds = [];
      tree.map((item) => {
        this.menuIds.push(item.id);
      });
      // console.log(this.menuIds);
    },
    // 状态修改
    async editStatus(id,status) {
      let query = {
        status: status,
      };

      let res = await editRoleStatus(id, query);
      if (res.code == 1) {
        this.$message.success("状态变更成功");
      } else {
        this.$message.error("状态变更失败");
        return;
      }
    },
    // 菜单分配
    async getRoleMenu(row) {
      this.menuData = [];
      this.currentMenu = [];
      let menuTree = await allMenuList();
      // console.log("全部菜单", menuTree.data);
      let res = await getListMenu(row.id);
      // console.log("角色相关菜单", res.data);

      if (menuTree.code == 1) {
        this.menuData = menuTree.data;
        res.data.map((item) => {
          this.currentMenu.push(item.id);
          // if (item.parentId == 0) {
          //   this.$set(item, "children", []);
          //   item.children = [];
          //   this.currentMenu.push(item);
          // }
          // this.currentMenu.map((father) => {
          //   if (father.id == item.parentId) {
          //     father.children.push(item);
          //   }
          // });
        });
        if (this.currentMenu.length > 0) {
          this.menuIds = this.currentMenu;
        }
        // console.log(this.currentMenu);
        this.roleID = row.id;
        this.menuShow = true;
      }
    },
    async menuAllocation() {
      let query = {
        menuIds: this.menuIds.join(","),
        roleId: this.roleID,
      };
      let res = await setMenu(query);
      if (res.code == 1) {
        this.menuShow = false;
        this.$message.success("分配资源成功");
        this.getAllRole();
      } else {
        this.menuShow = false;
        this.$message.error("分配资源失败");
        this.getAllRole();
      }
    },
    //角色相关资源获取
    async getRoleResources(row) {
      let all = await allResource(); //资源列表
      let res = await getListResource(row.id); //角色相关资源
      let resources = await searchResource(); //所有后台资源
      this.resourcesData = all.data;
      this.currentResources = [];
      if (all.code == 1) {
        this.resourcesShow = true;
        if (res.code == 1) {
          all.data.map((item) => {
            this.$set(item, "children", []);
            item.children = [];
            res.data.map((item2) => {
              if (item.id == item2.categoryId) {
                // console.log("子菜单", item);
                // item.children.push(item2);
                // let filterArr = [...new Set(all.data)];
                // this.resourcesData = filterArr;
                this.currentResources.push(item2.id);
              }
            });

            resources.data.map((item3) => {
              if (item.id == item3.categoryId) {
                item.children.push(item3);
              }
            });
          });
          // console.log("全部", this.resourcesData);
          if (this.currentResources.length > 0) {
            this.resourcesIds = this.currentResources;
          }
          console.log("选中的", this.currentResources);
          console.log("已有的", this.resourcesIds);
        }
      }
      this.roleID = row.id;
    },
    // 资源分配
    async resourcesAllocation() {
      this.loading = true;
      let query = {
        resourceIds: this.resourcesIds.join(","),
        roleId: this.roleID,
      };
      let res = await setResource(query);
      if (res.code == 1) {
        this.resourcesShow = false;
        this.$message.success("分配资源成功");
      } else {
        this.resourcesShow = false;
        this.$message.error("分配资源失败");
      }
      this.loading = false;
    },

    // 批量删除取消
    cancelDel() {
      this.selection = false;
    },
    // 批量删除确认
    async sbumitDel() {
      // console.log(this.delIds);
      // let ids = this.delIds.join(",");
      // console.log(ids);
      // let res = await selectionDelRole({ ids: ids });
      // if (res.code == 1) {
      //   this.$message.success("批量删除成功");
      //   this.getAllRole();
      // } else {
      //   this.$message.error("批量删除失败");
      //   this.getAllRole();
      // }
      this.$confirm("确定批量删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let ids = this.delIds.join(",");
          let res = await selectionDelRole({ ids: ids });
          if (res.code == 1) {
            this.$message.success("批量删除成功");
            this.getAllRole();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除角色选择
    SelectionChange(select) {
      this.delIds = [];
      select.map((item) => {
        // this.delIds=item.id ;
        this.delIds.push(item.id);
      });
      // console.log(this.delIds);
    },
    batchDelRole() {
      this.selection = true;
    },
    // 修改提交
     edit(createForm) {
            this.$refs[createForm].validate(async(valid) => {
        //开启校验
        if (valid) {
          // 如果校验通过，请求接口，允许提交表单
       let res = await editRole(this.editID, this.createForm);
      // console.log("修改成功", res);
      if (res.code == 1) {
        this.$message.success("角色修改成功");
        this.getAllRole();
        this.dialogFormVisible = false;
        this.createForm = {
          adminCount: "", //后台角色数量
          description: "", //角色描述
          name: "", //角色名称
          status: 1, //禁用/启用
        };
      } else {
        this.$message.error("角色修改失败");
        this.dialogFormVisible = false;
        this.createForm = {
          adminCount: "", //后台角色数量
          description: "", //角色描述
          name: "", //角色名称
          status: 1, //禁用/启用
        };
      }
        } else {
          //校验不通过
          return false;
        }
      });
      
    },
    // 对话框关闭
    closeDialog() {
            if (this.$refs.createForm) {
        this.$refs.createForm.resetFields();
      }
      // console.log("触发");
      this.isCreate = "";
      // this.diaTitle="";
      this.createForm = {
        adminCount: "", //后台角色数量
        description: "", //角色描述
        name: "", //角色名称
        status: "1", //禁用/启用
      };
    },
    // 修改角色
    editRole(row) {
      this.diaTitle = "角色修改";
      this.createForm = {
        adminCount: row.adminCount, //后台角色数量
        description: row.description, //角色描述
        name: row.name, //角色名称
        status: row.status, //禁用/启用
      };
      this.editID = row.id;
      // console.log("芜湖", this.editID);
      this.dialogFormVisible = true;
    },
    statusChange(e) {
      this.createForm.status = e;
    },
    // 获取所有角色
    async getAllRole() {
      this.loading = true;
      let res = await AllRole();
      // console.log("全部角色列表", res);
      if (res.code == 1) {
        this.tableData = res.data;
        // this.tableData = data.data.records.map((item,index) => {
        //   return {
        //     sortId:index + 1,
        //     ...item,
        //   }
        // })
      }
      this.loading = false;
    },
    // 添加角色
    async createRole() {
      const res = await createRole(this.createForm);
      // console.log("添加", res);
      if (res.code == 1) {
        this.$message.success("角色创建成功");
        this.getAllRole();
        this.dialogFormVisible = false;
        this.createForm = {
          adminCount: "", //后台角色数量
          description: "", //角色描述
          name: "", //角色名称
          status: 1, //禁用/启用
        };
      } else {
        this.$message.error("角色创建失败");
        this.dialogFormVisible = false;
        this.createForm = {
          adminCount: "", //后台角色数量
          description: "", //角色描述
          name: "", //角色名称
          status: 1, //禁用/启用
        };
      }
    },
    // 创建提交
    submitForm(createForm) {
            this.$refs[createForm].validate((valid) => {
        //开启校验
        if (valid) {
          // 如果校验通过，请求接口，允许提交表单
          this.createRole();
        } else {
          //校验不通过
          return false;
        }
      });
      
    },
  },
  computed: {},
  mounted() {},
  created() {
    this.getAllRole();
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tree-node,
/deep/ .custom-tree-node {
  margin-bottom: 10px;
}
label {
  font-weight: 700;
}
/deep/ .custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
}
/deep/ .el-dialog__footer {
  text-align: center;
}
/deep/ .el-table--border .el-table__cell:first-child .cell {
  padding-left: 0px;
}
/deep/ .el-table-column--selection .cell {
  padding-right: 10px;
}
</style>
